package com.cyz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.api.aliyunai.AliYunAiApi;
import com.cyz.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.cyz.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;
import com.cyz.exception.ThrowUtils;
import com.cyz.manager.FileManager;
import com.cyz.manager.upload.FilePictureUpload;
import com.cyz.manager.upload.UrlPictureUpload;
import com.cyz.model.dto.file.UploadPictureResult;
import com.cyz.model.dto.picture.*;
import com.cyz.model.entity.Picture;
import com.cyz.model.entity.Space;
import com.cyz.model.entity.User;
import com.cyz.model.enums.PictureReviewStausEnums;
import com.cyz.model.enums.UserRoleEnums;
import com.cyz.model.vo.PictureVO;
import com.cyz.model.vo.UserVO;
import com.cyz.service.PictureService;
import com.cyz.mapper.PictureMapper;
import com.cyz.service.SpaceService;
import com.cyz.service.UserService;
import com.cyz.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Resource
    FileManager fileManager;

    @Resource
    UserService userService;

    @Resource
    FilePictureUpload filePictureUpload;

    @Resource
    UrlPictureUpload urlPictureUpload;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 图片校验（更新和修改用户时用到）
     *
     * @param picture 图片信息
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 上传图片
     *
     * @param inputSource          图片输入源
     * @param pictureUploadRequest 上传图片请求
     * @param loginUser            操作用户
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 判断是否登录
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "未登录");
        // 判断是否是上传到私有空间
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            // 如果存在空间id，判断空间是否存在
            Space pictureSpace = spaceService.getById(spaceId);
            ThrowUtils.throwIf(pictureSpace == null, ErrorCode.PARAMS_ERROR, "该空间不存在");
            // 如果空间存在就校验该用户是否是空间所有者
            if (!loginUser.getId().equals(pictureSpace.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限操作该空间");
            }
            // 校验空间容量和图片数量
            if (pictureSpace.getTotalCount() >= pictureSpace.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间存储数量不足");
            }
            if (pictureSpace.getTotalSize() >= pictureSpace.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间存储容量不足");
            }
        }
        // 判断是上传图片还是更新图片
        Long pictureID = pictureUploadRequest.getId();
        // 如果是更新就判断图片是否存在
        if (pictureID != null) {
            Picture oldPicture = this.getById(pictureID);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "操作数据不存在");
            // 仅本人和管理员可更新图片
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 如果是更新就判断图片所在空间是否跟操作该图片的空间一致
            Long oldPictureSpaceId = oldPicture.getSpaceId();
            if (oldPictureSpaceId != null) {
                // 如果不为空就校验图片是否属于该操作空间
                if (spaceId == null) {
                    // 没传空间 ID 无权限修改该图片
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该图片");
                }
                ThrowUtils.throwIf(!oldPictureSpaceId.equals(spaceId), ErrorCode.NO_AUTH_ERROR, "没有操作该图片的权限");
            } else {
                // 如果要更新的图片的空间id为空（表示在公共空间），就将spaceId设置为空
                spaceId = null;
            }
        }

        // 文件路径前缀
        String uploadPathPrefix;
        if (spaceId == null) {
            // 如果spaceId为空就上传到公共图库
            uploadPathPrefix = String.format("/public/%s", loginUser.getId());
        } else {
            // 否则就上传到私有图库
            uploadPathPrefix = String.format("/space/%s", spaceId);
        }

        // 上传图片,并根据用户id划分目录,获取图片基本信息
        UploadPictureResult uploadPictureResult;
        if (inputSource instanceof String) {
            uploadPictureResult = urlPictureUpload.uploadPicture(inputSource, uploadPathPrefix);
        } else {
            uploadPictureResult = filePictureUpload.uploadPicture(inputSource, uploadPathPrefix);
        }
        // 将图片信息转换成数据库对象
        Picture picture = BeanUtil.copyProperties(uploadPictureResult, Picture.class);
        picture.setUserId(loginUser.getId());

        // 添加图片空间Id
        picture.setSpaceId(spaceId);
        // 设置用户传来的图片名称
        if (StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picture.setName(pictureUploadRequest.getPicName());
        }
        // 更新操作,补充信息
        Picture oldPicture = new Picture();
        if (pictureID != null) {
            // 如果是更新操作将id赋值给picture对象
            picture.setId(pictureID);
            picture.setEditTime(new Date());
            // 获取更新前的图片信息
            oldPicture = getById(pictureID);
            // 删除对象存储中的图片
            this.deletePictureFile(oldPicture);
        }
        // 填充审核信息
        fillReviewParam(picture, loginUser);

        // 开启事物
        Long finalSpaceId = spaceId;
        Picture finalOldPicture = oldPicture;
        transactionTemplate.execute(status -> {
            // 操作数据库
            // 判断是否是上传用户头像，避免将用户头像传到图片表，被其他用户看到
            if (!pictureUploadRequest.isUserAvatar()) {
                // 如果不是上传用户头像，可以保存到图片列表
                boolean res = saveOrUpdate(picture);// 根据是否有id来自动判断是更新还是新增操作
                ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");
            }
            // 更新空间额度
            if (finalSpaceId != null) {
                spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId)
                        // 如果是更新操作就减去上次图片的大小
                        .setSql(ObjUtil.isNotEmpty(pictureID), "totalSize = totalSize - " + finalOldPicture.getPicSize())
                        // 加上这次上传图片的大小
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        // 如果是更新操作就不加存储数量
                        .setSql(ObjUtil.isEmpty(pictureID), "totalCount = totalCount + 1").update();
            }
            return picture;
        });


        return PictureVO.objToVo(picture);
    }

    /**
     * 获取脱敏后的图片信息(单条)
     *
     * @param picture 未脱敏的图片信息
     * @return 脱敏后的信息
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        if (picture == null) return null;
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = pictureVO.getUserId();

        // 获取图片所有者信息
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        log.info("查询单个图片详情信息：{}", pictureVO);
        return pictureVO;
    }

    /**
     * 获取脱敏后的图片信息(多条)
     *
     * @param picturePage 未脱敏的图片信息
     * @return 脱敏后的信息
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        // 取出图片列表
        List<Picture> pictureList = picturePage.getRecords();
        // 判断列表是否为空
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }

        // 全部转换成VO
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());

        // 获取所有图片的所有者id
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        // 获取所有图片所有者信息
        Map<Long, List<User>> userMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 将信息与图片关联
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            // 在用户map中取出id相同的用户信息
            User user = null;
            if (userMap.containsKey(userId)) {
                user = userMap.get(userId).get(0);
            }
            // 将用户信息转换成VO，并分配给图片
            pictureVO.setUser(userService.getUserVO(user));
        });

        // 整合数据
        pictureVOPage.setRecords(pictureVOList);

        return pictureVOPage;
    }

    /**
     * 编辑图片
     *
     * @param pictureEditRequest 编辑图片请求
     * @param request            请求
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑，已改为使用注解鉴权
//        this.checkPictureAuth(loginUser, oldPicture);
        // 填充审核信息，如果是本人操作可以不需要审核
        this.fillReviewParam(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


    /**
     * 将查询数据转换成mp的查询条件
     *
     * @param pictureQueryRequest 查询请求
     * @return 查询条件
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        // 判断是否为空
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        // 获取参数所有字段
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        Date startEditTime = pictureQueryRequest.getStartEditTime();

        // 转换成查询条件类
        QueryWrapper<Picture> pictureQueryWrapper = new QueryWrapper<>();
        // 添加标签条件
        if (tags != null) {
            for (String tag : tags) {
                pictureQueryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 添加searchText条件（可以同时在图片名字和介绍中查询）
        if (searchText != null) {
            pictureQueryWrapper.and(qw -> qw.like("name", searchText).or().like("introduction", searchText));
        }
        // 添加其他查询参数并返回
        return pictureQueryWrapper.eq(ObjUtil.isNotNull(id), "id", id).eq(ObjUtil.isNotNull(userId), "userId", userId).like(StrUtil.isNotBlank(name), "name", name).like(StrUtil.isNotBlank(introduction), "introduction", introduction).like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat).eq(StrUtil.isNotBlank(category), "category", category).eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth).eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId).isNull(nullSpaceId, "spaceId").eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight).eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize).eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale).eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId).eq(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage).eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus).ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime).lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime).orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
    }


    /**
     * 删除图片
     *
     * @param pictureId 删除图片id
     * @param request   请求
     */
    @Override
    public boolean deletePictureById(Long pictureId, HttpServletRequest request) {
        // 数据校验
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        // 获取用户信息
        User loginUser = userService.getLoginUser(request);

        // 判断是否存在
        Picture oldPicture = getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验图片操作权限，已改为使用注解鉴权
//        this.checkPictureAuth(loginUser, oldPicture);
        // 开启事物
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

            if (oldPicture.getSpaceId() != null) {
                // 更新空间额度
                boolean res = spaceService.lambdaUpdate().eq(Space::getId, oldPicture.getSpaceId())
                        // 减去这张图片的大小
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        // 空间存储的数量减一
                        .setSql("totalCount = totalCount - 1").update();
                ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            // 删除COS对象存储中的图片
            this.deletePictureFile(oldPicture);
            return true;
        });
        return true;
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest 图片审核参数
     * @param request              请求
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        // 1.校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取登录用户信息
        User loginUser = userService.getLoginUser(request);
        Long pictureId = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStausEnums reviewStaus = PictureReviewStausEnums.getEnumByValue(reviewStatus);
        // 如果图片id为空或状态参数为待审核，抛出异常
        ThrowUtils.throwIf(pictureId == null || PictureReviewStausEnums.REVIEWING.equals(reviewStaus), ErrorCode.PARAMS_ERROR);

        // 2.判断图片是否存在
        Picture reviewingPicture = getById(pictureId);
        ThrowUtils.throwIf(reviewingPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 3.校验审核状态是否重复
        ThrowUtils.throwIf(reviewingPicture.getReviewStatus().equals(reviewStatus), ErrorCode.PARAMS_ERROR, "审核状态重复");

        // 4.更新数据库
        Picture updatedPicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatedPicture);
        updatedPicture.setReviewerId(loginUser.getId());
        updatedPicture.setReviewTime(new Date());
        ThrowUtils.throwIf(!updateById(updatedPicture), ErrorCode.OPERATION_ERROR);
    }

    /**
     * 填充审核参数
     *
     * @param picture   待审核图片
     * @param loginUser 操作用户
     */
    @Override
    public void fillReviewParam(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewStatus(PictureReviewStausEnums.PASS.getValue());
            picture.setReviewTime(new Date());
            picture.setReviewerId(loginUser.getId());
        } else {
            picture.setReviewStatus(PictureReviewStausEnums.REVIEWING.getValue());
        }
    }

    /**
     * 批量抓取图片
     *
     * @param pictureUploadByBatchRequest 批量抓取图片的请求参数
     * @param loginUser                   当前操作用户
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1. 校验参数
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "抓取数量不能超过三十条");
        // 2. 拼接要抓取的网页链接
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            // 3. 并使用Jsoup抓取数据
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("页面获取失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片抓取失败");
        }
        // 4. 解析抓取到的网页数据
        Element div = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(div == null, ErrorCode.OPERATION_ERROR, "图片抓取失败");
        Elements imgElementList = div.select("img.mimg");
        // 循环获取图片链接
        int uploadCount = 0;
        // 取出图片名称前缀，用来拼接用户指定的名称
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            // 默认为请求关键词
            namePrefix = pictureUploadByBatchRequest.getSearchText();
        }
        for (Element imgElement : imgElementList) {
            String pictureUrl = imgElement.attr("src");
            if (StrUtil.isBlank(pictureUrl)) {
                log.info("该链接为空：{}", pictureUrl);
                continue;
            }
            // 处理图片链接，防止转义或对象存储冲突
            int questionMarkIndex = pictureUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                pictureUrl = pictureUrl.substring(0, questionMarkIndex);
            }

            // 5. 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setPictureUrl(pictureUrl);
            // 设置图片名称
            pictureUploadRequest.setPicName(namePrefix + " " + (uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(pictureUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.info("上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 删除COS对象存储中的图片
     *
     * @param picture 要删除的图片对象
     */
    @Async  // 打开异步，可以在后台慢慢删除
    public void deletePictureFile(Picture picture) {

        // 判断图片是否被多条记录使用
        String pictureUrl = picture.getUrl();
        long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        if (count > 1) {
            // 如果有多个记录用到该图片，不清理
            return;
        }

        // 清理压缩后的图片
        String url = picture.getUrl();
        if (StrUtil.isNotBlank(url)) {
            fileManager.deleteObj(url);
        }
        // 清理缩略图
        String thumbnailUrl = picture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            fileManager.deleteObj(thumbnailUrl);
        }
        // 清理原图
        String originalUrl = picture.getOriginalUrl();
        if (StrUtil.isNotBlank(originalUrl)) {
            fileManager.deleteObj(originalUrl);
        }
    }

    /**
     * 校验图片操作权限
     *
     * @param loginUser 操作用户
     * @param picture   操作图片
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        // 获取图片空间id
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 空间Id为空就说明为公共图片，仅图片创建者和管理员可以操作
            if (!loginUser.getId().equals(picture.getUserId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 有id说明为私有图片，仅图所有者可操作
            if (!loginUser.getId().equals(picture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(picColor == null, ErrorCode.PARAMS_ERROR, "输入的颜色不能为空");
        // 构建图片查询参数
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        // 判断是否查询私有空间中的图片
        if (spaceId == null) {
            // 没有空间 Id 代表访问的是公共图片
            queryWrapper.isNull("spaceId");
        } else {
            Space space = spaceService.getById(spaceId);
            // 如果空间参数不为空，校验空间是否存在，并校验空间是否有图片
            ThrowUtils.throwIf(space == null || space.getTotalCount() == 0, ErrorCode.PARAMS_ERROR, "空间不存在或空间中没有图片");
            // 校验空户是否有权限访问该空间
            ThrowUtils.throwIf(!Objects.equals(space.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "没有权限访问该空间");
            // 将空间 Id 加入到查询参数中
            queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        }

        // 查询图片
        // 设置排序参数
        queryWrapper.orderBy(true, false, "createTime");
        List<Picture> pictureList = this.list(queryWrapper);

        // 返回主色调最接近的12个图片
        return pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
            String pictureColor = picture.getPicColor();
            // 判断图片是否有主色调
            if (pictureColor == null) {
                //如果为空就将图片放到最后一位
                return Double.MAX_VALUE;
            }
            // 计算所有图片颜色相似度，并根据图片相似度排序
            return -ColorSimilarUtils.calculateSimilarity(picColor, pictureColor);
        })).limit(12).map(PictureVO::objToVo).collect(Collectors.toList());
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        // 1. 校验参数
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR, "图片列表不能为空");
        ThrowUtils.throwIf(ObjUtil.isEmpty(loginUser), ErrorCode.NO_AUTH_ERROR);
        // 2. 判断用户是否有权限修改（修改私有空间）
        if (spaceId != null) {
            // 表明修改的是私有空间图片的信息,判断用户是否有权限
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(!Objects.equals(space.getUserId(), loginUser.getId()), ErrorCode.NO_AUTH_ERROR);
        } else {
            // 修改公共空间图片信息, 判断用户是否是管理员
            ThrowUtils.throwIf(!loginUser.getUserRole().equals(UserRoleEnums.ADMIN.getValue()), ErrorCode.NO_AUTH_ERROR);
        }

        // 4. 根据图片图片 Id 获取到所需的图片信息（图片名称，标签，分类）
        List<Picture> pictureList = lambdaQuery()
                .select(Picture::getId)
                .in(Picture::getId, pictureIdList)
                .list();

        // 5. 修改所有图片标签和分类
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        // 6. 修改所有图片的名称
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 7. 操作数据库批量更新
        boolean result = updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量操作失败");

    }

    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        // 校验参数
        if (CollUtil.isEmpty(pictureList)) {
            return;
        }

        // 替换名称中的规则
        int count = 1;
        try {
            for (Picture picture : pictureList) {
                // 处理规则
                String name = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(name);
            }
        } catch (Exception e) {
            log.error("名称解析失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析失败");
        }

    }

    /**
     * 创建 AI 扩图任务
     * @param createPictureOutPaintingTaskRequest 扩图请求参数
     * @param loginUser                           操作用户
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 校验参数
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        // 使用 Java8 中的Optional方法抛出异常
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));

        // 校验权限，已改为注解鉴权
//        checkPictureAuth(loginUser, picture);

        // 构造请求参数
        CreateOutPaintingTaskRequest.Parameters parameters = createPictureOutPaintingTaskRequest.getParameters();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getOriginalUrl());

        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(parameters);

        // 发送请创建 AI 扩图任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

}




